package com.sbpm.util;

import com.sencha.gxt.data.shared.loader.FilterConfig;

import javax.naming.InitialContext;
import javax.servlet.*;
import javax.transaction.*;
import java.io.IOException;

//@WebFilter(urlPatterns={"/*"}/*,
///initParams={ @WebInitParam(name="simpleParam", value="paramValue") }*/)
public class TransactionFilter implements Filter {


public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException 
{
	try
	{
		InitialContext ctx = new InitialContext();
		UserTransaction transactionManager = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
		try
		{
			transactionManager.begin();
			chain.doFilter(request, response);
			transactionManager.commit();
		}
		catch(RuntimeException e)
		{
			try {
				transactionManager.setRollbackOnly();
			} catch (IllegalStateException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SystemException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} catch (NotSupportedException e) {
			try {
				transactionManager.setRollbackOnly();
			} catch (IllegalStateException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SystemException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} catch (SystemException e) {
			try {
				transactionManager.setRollbackOnly();
			} catch (IllegalStateException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SystemException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} catch (RollbackException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HeuristicMixedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HeuristicRollbackException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	catch( Exception e )
	{
		e.printStackTrace();
	}

}

private FilterConfig filterConfig = null;

public void init(FilterConfig filterConfig)
throws ServletException 
{
	this.filterConfig = filterConfig;
}
public void destroy() {
	// TODO Auto-generated method stub
	
}
public void init(javax.servlet.FilterConfig arg0) throws ServletException {
	// TODO Auto-generated method stub
	
}


}